// 横向滚动动画核心逻辑
const startMarquee = (el, binding) => {
  const opt = {
    speed: binding.value?.speed || 60,       // 默认速度 (像素/秒)
    direction: binding.value?.direction || 'left', // 方向 left/right
    pauseOnHover: binding.value?.pauseOnHover ?? true // 悬停暂停
  }

  let offset = 0
  let paused = false
  let animationId = null

  // 动画循环
  const animate = () => {
    if (paused) return

    const direction = opt.direction === 'right' ? -1 : 1
    offset += (opt.speed * direction) / 60

    // 边界重置逻辑
    if (direction === 1) { // left 方向
      if (offset < -el.scrollWidth) offset = el.clientWidth
    } else { // right 方向
      if (offset > el.clientWidth) offset = -el.scrollWidth
    }

    el.style.transform = `translateX(${offset}px)`
    animationId = requestAnimationFrame(animate)
  }

  // 悬停控制
  if (opt.pauseOnHover) {
    el.addEventListener('mouseenter', () => paused = true)
    el.addEventListener('mouseleave', () => {
      paused = false
      animate()
    })
  }

  // 启动动画
  animate()

  // 保存动画引用以便销毁
  el._marquee_ = { animationId }
}

// 指令定义
const marquee = {
  inserted(el, binding) {
    // 初始化样式
    el.style.whiteSpace = 'nowrap'
    el.style.display = 'inline-block'
    el.parentElement.style.overflow = 'hidden'

    startMarquee(el, binding)
  },

  componentUpdated(el, binding) {
    // 参数变化时重启动画
    cancelAnimationFrame(el._marquee_.animationId)
    startMarquee(el, binding)
  },

  unbind(el) {
    // 清理资源
    cancelAnimationFrame(el._marquee_.animationId)
    el.removeEventListener('mouseenter')
    el.removeEventListener('mouseleave')
  }
}

export default marquee
